<?php  
/**
 * payment_method.php
 *
 * Payment method management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestKuaiqian extends RestController {
  public function tr3return() {
    $raw_post_data = file_get_contents("php://input");
    $data = $raw_post_data;
    preg_match("/<signature>(.*)<\/signature>/", $data, $signatureT);
    $signature = base64_decode($signatureT[1]);
    $data = str_replace($signatureT[0],"",$data);
    $fp = fopen(DIR_SYSTEM . "library/cert/vposPHP.cer", "r"); 
    $cert = fread($fp, 8192); 
    fclose($fp); 
    $pubkeyid = openssl_get_publickey($cert); 
    $ok = openssl_verify($data, $signature, $pubkeyid); 
    if($ok) {
      $data_2=$raw_post_data;
      $tr3_xml = simplexml_load_string($data_2);
      //根据externalRefNumber修改订单状态
      $order_id = $tr3_xml->TxnMsgContent->externalRefNumber->__toString();
      $this->changeOrderToProcessing($order_id);
      //返回tr4
      $tr4_xml_tpl = '<?xml version="1.0" encoding="UTF-8"?><MasMessage xmlns="http://www.99bill.com/mas_cnp_merchant_interface"><version>1.0</version><TxnMsgContent><txnType>PUR</txnType><interactiveStatus>TR4</interactiveStatus><merchantId>104110045112012</merchantId><terminalId>00002012</terminalId><refNumber>000012846461</refNumber></TxnMsgContent></MasMessage>';
      $tr4_xml = simplexml_load_string($tr4_xml_tpl);
      $tr4_xml->version = $tr3_xml->version;
      $tr4_xml->TxnMsgContent->txnType = $tr3_xml->TxnMsgContent->txnType;
      $tr4_xml->TxnMsgContent->merchantId = $tr3_xml->TxnMsgContent->merchantId;
      $tr4_xml->TxnMsgContent->terminalId = $tr3_xml->TxnMsgContent->terminalId;
      $tr4_xml->TxnMsgContent->refNumber = $tr3_xml->TxnMsgContent->refNumber;
      $export= $tr4_xml->asXml();
      echo $export;
    } elseif($ok == 0) {
      //验证失败
    } else {

    }
  }

  //获取用户名下已经保存的卡片
  public function getCardsList() {
    $this->checkPlugin();
    $json = array('success' => true);

    $customer_id = $this->customer->getId();

    $this->load->model('account/customer');
    $data = $this->model_account_customer->getCards($customer_id); 
    foreach ($data as $key => $value) {
       $data[$key]['display_card_no'] = '***'.substr($value['storable_card_no'], -4, 4);
    } 
    $json["data"] = $data;

    if ($this->debugIt) {
      echo '<pre>';
      print_r($json);
      echo '</pre>';
    } else {
      $this->response->setOutput(json_encode($json));
    }

  }

  public function getDynNum() {
    $this->checkPlugin();
    $json = array('success' => true);

    $order_info = $this->validatePay();
    $total = number_format($order_info['total'], 2, '.', '');
    
    $requestjson = file_get_contents('php://input');
    $post_data = json_decode($requestjson, true);

    $order_id = $this->session->data['order_id'];
    $this->load->library('kqquickpay');
    $config = array('customerId'=>$this->customer->getId(),
      'externalRefNumber'=>$order_id,
      'amount'=>$total);
    $this->kqquickpay = new Kqquickpay($config);

    if(isset($post_data['first']) && $post_data['first']==1) {
      //首次支付拿短信验证码
      $cardHolderName = $post_data['cardHolderName'];
      $cardHolderId = $post_data['cardHolderId'];
      $pan = $post_data['pan'];
      $phoneNO = $post_data['phoneNO'];
      $cvv2 = isset($post_data['cvv2'])?$post_data['cvv2']:'';
      $expiredDate = isset($post_data['expiredDate'])?$post_data['expiredDate']:'';
      $dynTr2Xml = $this->kqquickpay->getDynNum($cardHolderName, $cardHolderId, $pan, $phoneNO, $cvv2, $expiredDate);
    } else {
      //再次支付
      $storablePan = $post_data['storablePan'];
      $dynTr2Xml = $this->kqquickpay->getDynNum2($storablePan);
    }
    //分析dynTr2Xml返回值
    $dyn_tr2_xml = simplexml_load_string($dynTr2Xml);
    $responseCode = $dyn_tr2_xml->GetDynNumContent->responseCode->__toString();
    if($responseCode!='00') {
      $json['success']    = false;
      $json['error']['warning'] = $dyn_tr2_xml->GetDynNumContent->responseTextMessage->__toString();
    } else {
      $this->session->data['kq_sms_token'] = $dyn_tr2_xml->GetDynNumContent->token->__toString();
      $json['message'] = '短信发送成功';
    }

    $this->response->setOutput(json_encode($json));
    return;

    // header('Content-Type: application/xml');
    // print ($dynTr2Xml);
    // die();
  }

  public function pur() {
    $this->checkPlugin();
    $json = array('success' => true);

    $order_info = $this->validatePay();
    $total = number_format($order_info['total'], 2, '.', '');
    
    $requestjson = file_get_contents('php://input');
    $post_data = json_decode($requestjson, true);

    $order_id = $this->session->data['order_id'];
    $this->load->library('kqquickpay');
    $config = array('customerId'=>$this->customer->getId(),
      'externalRefNumber'=>$order_id,
      'amount'=>$total);
    $this->kqquickpay = new Kqquickpay($config);
    $tr3_url = $this->url->link('rest/kuaiqian/tr3return', '', 'SSL');
    $validCode = $post_data['validCode'];
    $token = $this->session->data['kq_sms_token'];
    if(isset($post_data['first']) && $post_data['first']==1) {
      //首次支付拿短信验证码
      $cardHolderName = $post_data['cardHolderName'];
      $cardHolderId = $post_data['cardHolderId'];
      $pan = $post_data['pan'];
      $phoneNO = $post_data['phoneNO'];
      $cvv2 = isset($post_data['cvv2'])?$post_data['cvv2']:'';
      $expiredDate = isset($post_data['expiredDate'])?$post_data['expiredDate']:'';
      $tr2Xml = $this->kqquickpay->pur($tr3_url, $validCode, $token, $cardHolderName, $cardHolderId, $pan, $phoneNO, $cvv2, $expiredDate);
    } else {
      //再次支付
      $storablePan = $post_data['storablePan'];
      $tr2Xml = $this->kqquickpay->pur2($tr3_url, $validCode, $token, $storablePan);
    }
    //分析tr2Xml返回值
    $tr2_xml = simplexml_load_string($tr2Xml);
    if($tr2_xml->ErrorMsgContent) {
      $json['success']    = false;
      $json['error']['warning'] = $tr2_xml->ErrorMsgContent->errorMessage->__toString();
    } else {
      $responseCode = $tr2_xml->TxnMsgContent->responseCode->__toString();
      if($responseCode!='00') {
        $json['success']    = false;
        $json['error']['warning'] = $tr2_xml->TxnMsgContent->responseTextMessage->__toString();
      } else {
        //保存短卡号
        if(isset($post_data['first']) && $post_data['first']==1) {
          $card_data = array();
          $card_data['customer_id'] = $tr2_xml->TxnMsgContent->customerId->__toString();
          $card_data['card_org'] = $tr2_xml->TxnMsgContent->cardOrg->__toString();
          $card_data['issuer'] = $tr2_xml->TxnMsgContent->issuer->__toString();
          $card_data['storable_card_no'] = $tr2_xml->TxnMsgContent->storableCardNo->__toString();
          $card_data['date_added'] = date('Y-m-d H:i:s');
          $this->load->model('account/customer');
          $this->model_account_customer->saveCard($card_data);  
        }
        // 处理订单
        $order_id = $tr2_xml->TxnMsgContent->externalRefNumber->__toString();
        $this->changeOrderToProcessing($order_id);

        $json['message'] = '支付成功';
      }
    }

    // header('Content-Type: application/xml');
    // print ($tr2Xml);
    // die();

    $this->response->setOutput(json_encode($json));
  }

  public function validatePay() {
    $json = array();
    //检查是否有订单号且订单是否属于当前用户
    if(!isset($this->session->data['order_id'])) {
      $json['error'] = '未找到订单号';
    }
    $order_id = $this->session->data['order_id'];
    $this->load->model('account/order');
    $order_info = $this->model_account_order->getOrderWithStatusZero($order_id);
    if (!$order_info) {
      $json['error'] = '未找到订单';
    }
    if(isset($json["error"])){
      echo(json_encode($json));
      exit;
    }
    return $order_info;
  }

  private function changeOrderToProcessing($order_id) {
    $this->load->model('checkout/order');

    $order_info = $this->model_checkout_order->getOrder($order_id);
    
    if($order_info) {
      //之后换成快钱payment_status
      $order_status_id = $this->config->get('kuaiqian_order_status_id');
      if (!$order_info['order_status_id'] || $order_info['order_status_id'] != $order_status_id) {
        $this->model_checkout_order->addOrderHistory($order_id, $order_status_id, '', true);
      }
    }
  }

}